package com.tz.crm.components;

import org.apache.log4j.Logger;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * 配置 SessionFactory 的封装类(FactoryBean)
 *
 * @author HuJingling
 * @since 2017/1/19
 */
@Component("sessionFactory")
public class MyLocalSessionFactoryBean extends LocalSessionFactoryBean {

    private static final Logger LOGGER = Logger.getLogger(MyLocalSessionFactoryBean.class);

    /**
     * 构造函数
     *
     * @param dataSource        DataSource
     * @param entityInterceptor EntityInterceptor
     * @param env               Environment
     */
    @Inject
    public MyLocalSessionFactoryBean(DataSource dataSource, EntityInterceptor entityInterceptor, Environment env) {
        LOGGER.debug("LocalSessionFactoryBean init...");
        //1.设置数据源
        this.setDataSource(dataSource);
        //2.方言
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", env.getProperty("jpa.properties.hibernate.dialect"));
        props.setProperty("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
        props.setProperty("hibernate.format_sql", env.getProperty("spring.jpa.format_sql"));
        props.setProperty("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
        setHibernateProperties(props);
        //3.注册实体类
        this.setPackagesToScan("com.tz.crm.entity");
        //setEntityInterceptor
        boolean interceptorEnable = env.getProperty("hibernate.interceptor.enable", Boolean.class, true);
        if (interceptorEnable) {
            LOGGER.trace("setEntityInterceptor:" + entityInterceptor);
            this.setEntityInterceptor(entityInterceptor);
        }
    }

}
